<template>
  <view class="category-page">
    <!-- 顶部搜索栏 -->
    <view class="top-bar">
      <view class="title">商品分类</view>
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input class="search-input" placeholder="搜索商品" v-model="searchKeyword" @input="onSearch" />
      </view>
    </view>

    <!-- 主体内容区 -->
    <view class="main-content">
      <!-- 左侧分类导航 -->
      <view class="category-sidebar">
        <view 
          v-for="(category, index) in categoryList" 
          :key="category.id"
          :class="['category-item', { active: currentCategoryIndex === index }]"
          @click="switchCategory(index)"
        >
          {{ category.categoryName }}
        </view>
        
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-tip">
          <text>加载中...</text>
        </view>
        
        <!-- 空状态 -->
        <view v-if="!loading && categoryList.length === 0" class="empty-tip">
          <text>暂无分类数据</text>
        </view>
      </view>

      <!-- 右侧商品展示区 -->
      <view class="product-content">
        <!-- 轮播图/广告图 -->
        <view class="banner-section" v-if="currentBanner">
          <image class="banner-img" :src="currentBanner.image" mode="aspectFill"></image>
          <view class="banner-info">
            <view class="banner-title">{{ currentBanner.title }}</view>
            <view class="banner-desc">{{ currentBanner.desc }}</view>
            <view class="banner-price">{{ currentBanner.price }}</view>
          </view>
        </view>

        <!-- 商品分类展示 -->
        <view class="product-sections">
          <view 
            v-for="(section, sectionIndex) in currentProductSections" 
            :key="sectionIndex"
            class="product-section"
          >
            <view class="section-title">{{ section.title }}</view>
            <view class="product-grid">
              <view 
                v-for="(product, productIndex) in section.products" 
                :key="product.id || productIndex"
                class="product-item"
                @click="goToProduct(product)"
              >
                <image class="product-img" :src="product.mainImage || product.thumbnail || '/static/img/a.png'" mode="aspectFill"></image>
                <text class="product-name">{{ product.productName }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 商品加载状态 -->
        <view v-if="loading" class="loading-tip">
          <text>加载商品中...</text>
        </view>
        
        <!-- 商品空状态 -->
        <view v-if="!loading && currentProductSections.length === 0" class="empty-tip">
          <text>该分类下暂无商品</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { get } from '@/config/request.js'

export default {
  data() {
    return {
      searchKeyword: '', // 搜索关键词
      currentCategoryIndex: 0, // 当前选中的分类索引
      
      // 分类列表 - 从接口获取
      categoryList: [],
      
      // 当前分类的广告图
      currentBanner: null,
      
      // 当前分类的商品分类展示
      currentProductSections: [],
      
      // 加载状态
      loading: false
    }
  },
  
  onLoad() {
    // 页面加载时获取分类数据
    this.getCategoryData()
  },
  
  methods: {
    // 搜索功能
    onSearch() {
      console.log('搜索关键词:', this.searchKeyword)
      if (this.searchKeyword.trim()) {
        this.searchProducts(this.searchKeyword)
      }
    },
    
    // 切换分类
    switchCategory(index) {
      this.currentCategoryIndex = index
      const category = this.categoryList[index]
      console.log('切换到分类:', category.categoryName)
      
      // 根据分类获取对应的商品数据
      this.getProductsByCategory(category.id)
    },
    
    // 跳转到商品详情 - 跳转到goumaishangpin页面
    goToProduct(product) {
      console.log('跳转到商品:', product)
      
      // 跳转到goumaishangpin页面，传递商品ID
      uni.navigateTo({
        url: `/pages/goumaishangpin/goumaishangpin?id=${product.id}`
      })
    },
    
    // 获取分类数据
    async getCategoryData() {
      try {
        this.loading = true
        console.log('开始获取分类数据...')
        
        const response = await get('/shangpin/classify/list', {
          status: 'enabled', // 只获取启用的分类
          level: 1 // 获取一级分类
        })
        
        console.log('分类接口响应:', response)
        
        if (response.code === 200 && response.rows) {
          // 将后端字段映射到前端字段
          this.categoryList = response.rows.map(category => ({
            id: category.id,
            categoryName: category.categoryName,
            icon: category.categoryIcon,
            level: category.level,
            parentId: category.parentId,
            sortOrder: category.sortOrder,
            status: category.status
          }))
          
          console.log('处理后的分类数据:', this.categoryList)
          
          // 如果有分类数据，获取第一个分类的商品
          if (this.categoryList.length > 0) {
            this.getProductsByCategory(this.categoryList[0].id)
          }
        } else {
          console.error('获取分类数据失败:', response.msg)
          uni.showToast({
            title: response.msg || '获取分类数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取分类数据异常:', error)
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 根据分类获取商品数据
    async getProductsByCategory(categoryId) {
      try {
        this.loading = true
        console.log('开始获取分类商品数据，分类ID:', categoryId)
        
        // 获取子分类
        const subCategoriesResponse = await get('/shangpin/classify/list', {
          parentId: categoryId,
          status: 'enabled'
        })
        
        console.log('子分类接口响应:', subCategoriesResponse)
        
        if (subCategoriesResponse.code === 200 && subCategoriesResponse.rows) {
          const subCategories = subCategoriesResponse.rows
          const sections = []
          
          // 为每个子分类获取商品
          for (const subCategory of subCategories) {
            console.log('获取子分类商品:', subCategory.categoryName)
            
            const productsResponse = await get('/shangpin/platform/list', {
              categoryId: subCategory.id,
              status: 1, // 上架状态
              pageSize: 6 // 每个分类显示6个商品
            })
            
            console.log('商品接口响应:', productsResponse)
            
            if (productsResponse.code === 200 && productsResponse.rows) {
              sections.push({
                title: subCategory.categoryName,
                products: productsResponse.rows.map(product => ({
                  id: product.id,
                  productName: product.productName,
                  mainImage: product.mainImage,
                  thumbnail: product.thumbnail,
                  price: product.price,
                  originalPrice: product.originalPrice,
                  stock: product.stock,
                  soldNum: product.soldNum
                }))
              })
            }
          }
          
          this.currentProductSections = sections
          console.log('处理后的商品数据:', this.currentProductSections)
          
          // 更新广告图（可以根据分类动态设置）
          this.updateBannerByCategory(categoryId)
        } else {
          console.log('没有子分类，尝试直接获取该分类下的商品')
          // 如果没有子分类，直接获取该分类下的商品
          const productsResponse = await get('/shangpin/platform/list', {
            categoryId: categoryId,
            status: 1, // 上架状态
            pageSize: 20
          })
          
          if (productsResponse.code === 200 && productsResponse.rows) {
            this.currentProductSections = [{
              title: '商品列表',
              products: productsResponse.rows.map(product => ({
                id: product.id,
                productName: product.productName,
                mainImage: product.mainImage,
                thumbnail: product.thumbnail,
                price: product.price,
                originalPrice: product.originalPrice,
                stock: product.stock,
                soldNum: product.soldNum
              }))
            }]
          } else {
            this.currentProductSections = []
          }
        }
      } catch (error) {
        console.error('获取分类商品数据异常:', error)
        uni.showToast({
          title: '获取商品数据失败，请稍后重试',
          icon: 'none'
        })
        this.currentProductSections = []
      } finally {
        this.loading = false
      }
    },
    
    // 根据分类更新广告图
    updateBannerByCategory(categoryId) {
      // 这里可以根据分类ID设置不同的广告图
      // 暂时隐藏广告图
      this.currentBanner = null
    },
    
    // 搜索商品
    async searchProducts(keyword) {
      try {
        this.loading = true
        console.log('开始搜索商品:', keyword)
        
        const response = await get('/shangpin/platform/list', {
          productName: keyword,
          status: 1,
          pageSize: 20
        })
        
        console.log('搜索接口响应:', response)
        
        if (response.code === 200 && response.rows) {
          // 将搜索结果转换为分类展示格式
          this.currentProductSections = [{
            title: `搜索"${keyword}"的结果`,
            products: response.rows.map(product => ({
              id: product.id,
              productName: product.productName,
              mainImage: product.mainImage,
              thumbnail: product.thumbnail,
              price: product.price,
              originalPrice: product.originalPrice,
              stock: product.stock,
              soldNum: product.soldNum
            }))
          }]
          
          // 隐藏广告图
          this.currentBanner = null
        } else {
          this.currentProductSections = [{
            title: `搜索"${keyword}"的结果`,
            products: []
          }]
          this.currentBanner = null
        }
      } catch (error) {
        console.error('搜索商品异常:', error)
        uni.showToast({
          title: '搜索失败，请稍后重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.category-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #f8f9fa 0%, #f5f5f5 100%);
}

/* 顶部搜索栏 */
.top-bar {
  display: flex;
  align-items: center;
  padding: 25rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
}

.title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-right: 30rpx;
}

.search-box {
  flex: 1;
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #f8f9fa, #f0f0f0);
  border-radius: 25rpx;
  padding: 12rpx 20rpx;
  margin-right: 20rpx;
  box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  margin-left: 10rpx;
}

.top-actions {
  display: flex;
  gap: 20rpx;
}

/* 主体内容区 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧分类导航 */
.category-sidebar {
  width: 200rpx;
  background-color: #fff;
  overflow-y: auto;
  box-shadow: 2rpx 0 8rpx rgba(0, 0, 0, 0.05);
}

.category-item {
  padding: 32rpx 20rpx;
  font-size: 28rpx;
  color: #666;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
  transition: all 0.3s ease;
}

.category-item:active {
  background-color: rgba(255, 77, 79, 0.05);
}

.category-item.active {
  color: #ff4d4f;
  background: linear-gradient(90deg, rgba(255, 77, 79, 0.05), transparent);
  font-weight: bold;
}

.category-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 44rpx;
  background: linear-gradient(180deg, #ff4d4f, #ff6b6b);
  border-radius: 0 4rpx 4rpx 0;
}

/* 右侧商品展示区 */
.product-content {
  flex: 1;
  background-color: #f5f5f5;
  overflow-y: auto;
  padding: 30rpx 20rpx;
}

/* 轮播图/广告图 */
.banner-section {
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  margin-bottom: 30rpx;
  position: relative;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.banner-section:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.12);
}

.banner-img {
  width: 100%;
  height: 320rpx;
}

.banner-info {
  padding: 25rpx;
}

.banner-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
}

.banner-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 12rpx;
  line-height: 1.4;
}

.banner-price {
  font-size: 30rpx;
  color: #ff4d4f;
  font-weight: bold;
  background: linear-gradient(135deg, #ff4d4f, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 商品分类展示 */
.product-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 25rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.product-section:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.12);
}

.section-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 25rpx;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -8rpx;
  left: 0;
  width: 40rpx;
  height: 4rpx;
  background: linear-gradient(90deg, #ff4d4f, #ff6b6b);
  border-radius: 2rpx;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 25rpx;
}

.product-item {
  width: calc(33.33% - 17rpx);
  text-align: center;
  padding: 25rpx 15rpx;
  border-radius: 16rpx;
  background: linear-gradient(135deg, #fafafa, #f5f5f5);
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.product-item:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.product-img {
  width: 130rpx;
  height: 130rpx;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.product-name {
  font-size: 26rpx;
  color: #333;
  line-height: 1.3;
  font-weight: 500;
}

/* 加载状态和空状态样式 */
.loading-tip, .empty-tip {
  padding: 30rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>